﻿using System;

namespace AcademicPlanner.Domain
{
	/// <summary>
	/// Task is the base class for all data changing operations in the
	/// AcademicPlanner application's domain layer. A Task is a way of
	/// atomitising a data changing operation by adding some transaction
	/// support to it.
	/// </summary>
	/// <version>1.0</version>
	/// <since>1.0</since>
	abstract class Task
	{
		/// <summary>
		/// Whether the Task succeeed without any errors or not.
		/// </summary>
		/// <version>1.0</version>
		/// <since>1.0</since>
		protected bool _succeeded;


		/// <summary>
		/// Gets the <c>DomainMaster</c> of the AcademicPlanner application.
		/// </summary>
		/// <version>1.0</version>
		/// <since>1.0</since>
		protected DomainMaster DomainMaster { get { return DomainMaster.GetInstance(); } }


		/// <summary>
		/// Runs a Task. The Task is initialized, performed and completed.
		/// If no exception is thrown during the running of the Task, the
		/// <c>_succeeded</c> field is set to <c>true</c>.
		/// </summary>
		/// <seealso cref="M:Init"/>
		/// <seealso cref="M:Perform"/>
		/// <seealso cref="M:Complete"/>
		/// <version>1.0</version>
		/// <since>1.0</since>
		public void Run()
		{
			try
			{
				Init();
				Perform();
				_succeeded = true;
			}
			finally
			{
				Complete();
			}
		}

		/// <summary>
		/// Initializes this Task by getting the data layer ready for transaction
		/// oriented operations.
		/// </summary>
		/// <seealso cref="P:DomainMaster.DSAS"/>
		/// <seealso cref="M:AcademicPlanner.Data.DataSourceAccessSupervisor.PrepareForWork"/>
		/// <version>1.0</version>
		/// <since>1.0</since>
		protected virtual void Init()
		{
			DomainMaster.DSAS.PrepareForWork();
		}

		/// <summary>
		/// Completes this Task by getting the data layer clean up after transaction
		/// oriented operations based on <c>_succeeded</c> field.
		/// </summary>
		/// <seealso cref="P:DomainMaster.DSAS"/>
		/// <seealso cref="M:AcademicPlanner.Data.DataSourceAccessSupervisor.CleanUpAfterWork"/>
		/// <version>1.0</version>
		/// <since>1.0</since>
		protected virtual void Complete()
		{
			DomainMaster.DSAS.CleanUpAfterWork(_succeeded);
		}

		/// <summary>
		/// Performs this Task's bulk work. This method is abstract.
		/// </summary>
		/// <version>1.0</version>
		/// <since>1.0</since>
		protected abstract void Perform();
	}
}
